<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;

class CheckJwt
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {

        //jwt验证
        //允许的源域名
        // header("Access-Control-Allow-Origin: *");
        // //允许的请求头信息
        // header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
        // //允许的请求类型
        // header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');

        // 本地测试没问题，但是线上测试需要写在=>config/cors.php中

        try {
            $appkey = $request->header('appkey');
            if (empty($appkey)) {
                $this->failed('appkey不能为空!', 403);die();
            }
            // $appkey = JwtController::verifyToken($appkey);
            // //登录验证
            // if (empty($appkey)) {
            //     $this->failed('未登录或appkey无效', 403);die();
            // }
            //判断是否是会员权限
            $users = new User();
            $res = $users->where('appkey', $appkey)
                ->get();

            $viptime = $res[0]->viptime;
            if ($viptime < time()) {
                $this->failed('appkey过期，请充值', 403);die();
            }

            //将获取的用户id 设置到请求信息中
            $request->merge(['appkey' => $appkey]);

        } catch (\Exception $e) {
            $this->failed('服务异常，请检查appkey令牌', 403);die();
        }
        return $next($request);

    }

/**
 * 通用响应
 * @param int $code 错误码
 * @param string $msg 错误描述
 * @param array $data 返回数据
 */
    public function response($code = 200, $msg = 'success', $data = [])
    {
        $res = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];
        //以下两行二选一
        echo json_encode($res, JSON_UNESCAPED_UNICODE);
        //json($res)->send();die;
    }
    /**
     * 失败时响应
     * @param string $msg 错误描述
     * @param int $code 错误码
     */
    public function failed($msg = 'fail', $code = 400)
    {
        return $this->response($code, $msg);
    }

    /**
     * 成功时响应
     * @param array $data 返回数据
     * @param int $code 错误码
     * @param string $msg 错误描述
     */
    public function ok($data = [], $code = 200, $msg = 'success')
    {
        return $this->response($code, $msg, $data);
    }

}
